package cloud.lysky.java.on.concurrent.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author luoly
 * @describe
 * @date 2023/3/19 13:06
 **/
// Semaphore实现服务接口限流
public class ServiceLimitDemo {
    public static void main(String[] args) {
        // 模拟10个线程同时请求服务
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new ServiceRequest(), "Thread-" + i);
            thread.start();
        }
    }

    static class ServiceRequest implements Runnable {
        private static final Semaphore semaphore = new Semaphore(3);

        @Override
        public void run() {
            try {
                // 尝试获取许可证
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + "请求服务，当前服务可用");
                // 模拟服务处理时间
                Thread.sleep(3000);
                System.out.println(Thread.currentThread().getName() + "处理完服务，释放许可证");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放许可证
                semaphore.release();
            }
        }
    }
}
